//
//  YWCirculationOfRecordViewController.m
//  maintain
//
//  Created by Kyo on 16/9/30.
//  Copyright © 2016年 ewin. All rights reserved.
//

#import "YWCirculationOfRecordViewController.h"
#import "MJRefresh.h"
#import "UIColor+CustomColors.h"
#import "UIScrollView+EmptyDataSet.h"

#import "YWCirculationInfo.h"
#import "YWCirculationManager.h"
#import "YWCommonTool.h"
#import "YWMacro.h"
#import "YWMission.h"
#import "YWLoginUser.h"
#import "YWLoginTool.h"
#import "YWHandler.h"

#import "YWMissionManager.h"

#import "UITableView+FDTemplateLayoutCell.h"
#import "YWTroubleMissionFinishBillCell.h"
#import "YWNewCirculationButtonCell.h"
#import "YWPostTroubleBillCell.h"
#import "YWTroubleMutableBIllCell.h"
#import "YWObserveTableViewCell.h"
#import "YWMeterReadingDetailRecordCell.h"
#import "YWNewReplyTableViewCell.h"

#import "YWEquipmentTroubleRecord.h"
#import "YWEquipmentFieldRecord.h"
#import "YWEquipmentType.h"
#import "YWEquipment.h"
#import "YWLocation.h"
#import "YWReportTroubleModel.h"
#import "YWTroubleMissionModel.h"
#import "YWEquipmentTroubleRecord.h"
#import "YWTroubleMissionManager.h"

@interface YWCirculationOfRecordViewController ()<UITableViewDataSource, UITableViewDelegate, DZNEmptyDataSetDelegate, DZNEmptyDataSetSource,UIAlertViewDelegate,YWPostTroubleBillCellDelegate>{
    BOOL showTopLine;
    BOOL showBottomLine;
    UIWebView *phoneCallWebView;
}
@property (nonatomic, strong) UITableView* tableView;
@property (nonatomic, strong) NSMutableArray* dataSource;
@property (nonatomic, strong) NSArray *replyArray;//评论数组
@property (nonatomic, strong) NSArray *circulationsArray;

@property (nonatomic, copy) NSString *fieldRecordContent;

@property (nonatomic, strong) UILabel *tableHeadLabel;

@end

@implementation YWCirculationOfRecordViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = @"故障详情";
    self.view.backgroundColor = [UIColor customBackgroudColor];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.tableView.backgroundColor = [UIColor customBackgroudColor];
    [self.tableView registerClass:[YWObserveTableViewCell class] forCellReuseIdentifier:YWObserveTableViewCellIdentifier];
    [self.tableView registerClass:[YWNewReplyTableViewCell class] forCellReuseIdentifier:YWNewReplyTableViewCellIdetifer];
    [self.tableView registerClass:[YWMeterReadingDetailRecordCell class] forCellReuseIdentifier:YWMeterReadingDetailRecordCellIdentifier];
    self.tableView.tableHeaderView = self.tableHeadLabel;
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, KbottomViewH)];
    self.tableView.estimatedRowHeight = 60.0f;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    if (self.troubleMissionModel.trouble.troubleId>0) {
        self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshTop)];
        // 马上进入刷新状态
        [self.tableView.mj_header beginRefreshing];
    }
}

- (void)refreshCirculationDetailVC{
    _dataSource = nil;
    [self.tableView reloadData];
}

- (void)refreshTableView:(NSNotification*)noti{
    //完成任务的推送
    if ([noti.object isKindOfClass:[YWTroubleMissionModel class]]) {
        YWTroubleMissionModel* updateMission = (YWTroubleMissionModel*)noti.object;
        if (self.troubleMissionModel.trouble.troubleId == updateMission.trouble.troubleId) {
            self.troubleMissionModel = updateMission;
            _dataSource = nil;
            [self.tableView reloadData];
        }
    }
}

- (void)refreshTop{
    YWWeakSelf(weakSelf);
    [[YWCirculationManager shareManager] requestCirculationInfoOfRecordWithTroubleId:weakSelf.troubleMissionModel.trouble.troubleId WithComplete:^(YWEquipmentTroubleRecordJson *equipmentTroubleRecord) {
        //equipmentTroubleRecord包含维修记录，trouble对象，troubleMission对象
        [weakSelf.tableView.mj_header endRefreshing];
        
        YWTroubleMissionModel * troubleMissionModel = weakSelf.troubleMissionModel;
        if (equipmentTroubleRecord) {
            if (troubleMissionModel.trouble.reporter==nil) {
                troubleMissionModel.trouble.reporter = equipmentTroubleRecord.trouble.reporter;
            }
            troubleMissionModel.trouble.channel = equipmentTroubleRecord.trouble.channel;
            troubleMissionModel.trouble.troubleContact = equipmentTroubleRecord.trouble.troubleContact;
            troubleMissionModel.trouble.troubleSequence = equipmentTroubleRecord.trouble.troubleSequence;
            troubleMissionModel.troubleStatus = equipmentTroubleRecord.troubleMission.troubleStatus;
            weakSelf.tableHeadLabel.attributedText = [YWCommonTool labelAttributedStringWithFristStr:@"编号: " secondStr:weakSelf.troubleMissionModel.trouble.troubleSequence?:@"无" secondColor:[UIColor customYellowColor]];
            troubleMissionModel.trouble.equipment = equipmentTroubleRecord.trouble.equipment;
            troubleMissionModel.trouble.location = equipmentTroubleRecord.trouble.location;
            troubleMissionModel.createTime = equipmentTroubleRecord.troubleMission.createTime;
            troubleMissionModel.trouble.reportTime = equipmentTroubleRecord.trouble.reportTime;
            troubleMissionModel.updateTime = equipmentTroubleRecord.troubleMission.updateTime;
            troubleMissionModel.executor = equipmentTroubleRecord.troubleMission.executor;
            troubleMissionModel.trouble.note = equipmentTroubleRecord.trouble.note;
            
            weakSelf.dataSource = nil;
            NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"createTime" ascending:NO];
            NSArray *sortArray = [equipmentTroubleRecord.trouble.circulationInfos sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];
            weakSelf.circulationsArray = sortArray;
            if (weakSelf.circulationsArray) {
                [weakSelf.dataSource addObject:weakSelf.circulationsArray];
            }
            _fieldRecordContent = nil;
            [weakSelf setUpDataSource];
            [weakSelf.tableView reloadData];
        }else{
            weakSelf.dataSource = nil;
            NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"createTime" ascending:NO];
            NSArray *sortArray = [weakSelf.troubleMissionModel.trouble.circulationInfos sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];
            weakSelf.circulationsArray = sortArray;
            if (weakSelf.circulationsArray) {
                [weakSelf.dataSource addObject:weakSelf.circulationsArray];
            }
            _fieldRecordContent = nil;
            [weakSelf setUpDataSource];
            [weakSelf.tableView reloadData];
        }
    }];
}


-(UILabel *)tableHeadLabel{
    if (!_tableHeadLabel) {
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 40)];
        label.font = KTitleFont;
        label.textAlignment = NSTextAlignmentCenter;
        label.backgroundColor = [UIColor whiteColor];
        label.attributedText = [YWCommonTool labelAttributedStringWithFristStr:@"编号: " secondStr:self.troubleMissionModel.trouble.troubleSequence?:@"无" secondColor:[UIColor customYellowColor]];
        _tableHeadLabel = label;
    }
    return _tableHeadLabel;
}


- (UITableView*)tableView
{
    if (!_tableView) {
        UITableView* tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64) style:UITableViewStyleGrouped];
        tableView.sectionFooterHeight = 1.0;
        tableView.delegate = self;
        tableView.dataSource = self;
        [self.view addSubview:tableView];
        _tableView = tableView;
        _tableView.emptyDataSetDelegate = self;
        _tableView.emptyDataSetSource = self;
        [_tableView registerClass:[YWPostTroubleBillCell class] forCellReuseIdentifier:YWPostTroubleBillCellIdentifier];
        [_tableView registerClass:[YWTroubleMissionFinishBillCell class] forCellReuseIdentifier:YWTroubleMissionFinishBillCellIdentifier];
        [_tableView registerClass:[YWTroubleMutableBIllCell class] forCellReuseIdentifier:YWTroubleMutableBIllCellIdentifier];
        [_tableView registerClass:[YWNewCirculationButtonCell class] forCellReuseIdentifier:YWNewCirculationButtonCellIdentifier];
    }
    return _tableView;
}
- (NSString *)fieldRecordContent{
    if (!_fieldRecordContent) {
        //设备参数
        YWEquipmentTroubleRecord* troubleRecord = [[YWTroubleMissionManager shareManager] troubleRecordWithMissionId:_troubleMissionModel.trouble.troubleId];
        NSArray *fieldRecordArray = troubleRecord.equipmentFieldRecord;
        if (fieldRecordArray.count == 0) {
            fieldRecordArray = [[YWMissionManager shareManager] equipmentFieldRecordsWithUniqueTag:troubleRecord.uniqueTag maintenanceTypeId:YWMaintenanceTypeTrouble];
        }
        NSMutableString *contenStr = [NSMutableString string];
        if (fieldRecordArray.count) {
            __block NSString *str = nil;
            [fieldRecordArray enumerateObjectsUsingBlock:^(YWEquipmentFieldRecord*  _Nonnull fieldrecord, NSUInteger idx, BOOL * _Nonnull stop) {
                if (idx != 0) {
                    [contenStr appendString:@"\n"];
                }
                if (fieldrecord.fieldTypeId == YWEquipmentFieldTypeIdDownSelect) {
                    str = [NSString stringWithFormat:@"%@: %@",fieldrecord.fieldName,fieldrecord.fieldOption.fieldOptionText?:@"未填写"];
                }else{
                    str = [NSString stringWithFormat:@"%@: %@",fieldrecord.fieldName,fieldrecord.fieldValue?:@"未填写"];
                }
                [contenStr appendString:str];
            }];
        }else{
            [contenStr appendString:@"无"];
        }
        _fieldRecordContent = [NSString stringWithFormat:@"%@",contenStr];
    }
    return _fieldRecordContent;
}
- (NSMutableArray*)dataSource
{
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
        if (self.troubleMissionModel) {
            NSMutableArray *firstArray = [NSMutableArray array];
            [firstArray addObject:self.troubleMissionModel];
            [_dataSource addObject:firstArray];
            if (self.troubleMissionModel.troubleStatus == YWTroubleMissionStatusFinish) {
                [firstArray addObject:self.troubleMissionModel];
            }
        }
        NSMutableArray *obserAndRepArray = [NSMutableArray array];
        [obserAndRepArray addObject:@""];//此为参与人row
        if (self.replyArray.count>0) {
            [obserAndRepArray addObject:@""];//“评论”row
            [obserAndRepArray addObjectsFromArray:self.replyArray];
        }
        [_dataSource addObject:obserAndRepArray];//参与人以及评论section
    }
    
    return _dataSource;
    
}

- (void)setUpDataSource{
    //YWLoginUser *currentUser = self.currentUser;
    
    __block NSUInteger isLastAssignIdx = 0;
    [_circulationsArray enumerateObjectsUsingBlock:^(YWCirculationInfo*  _Nonnull circulationInfo, NSUInteger idx, BOOL * _Nonnull stop) {
        if (circulationInfo.type == YWCirculationInfoTypeAssignTroubleMission){
            isLastAssignIdx = idx;
            *stop = YES;
        }
    }];
    if (_circulationsArray.count) {
        YWCirculationInfo *circulationInfo = isLastAssignIdx>0?_circulationsArray[isLastAssignIdx]:nil;
        circulationInfo.isLastAssignBill = circulationInfo?YES:NO;
    }

    
}

#pragma mark - UITableViewDataSource mothods
- (NSInteger)numberOfSectionsInTableView:(UITableView*)tableView
{
    return self.dataSource.count;
}

- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section
{
    NSArray *sectionCount = self.dataSource[section];
    return sectionCount.count;
}
- (CGFloat)tableView:(UITableView*)tableView heightForHeaderInSection:(NSInteger)section
{
    return section==0?0.01: 10;
}
- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath
{
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            YWPostTroubleBillCell* cell = [tableView dequeueReusableCellWithIdentifier:YWPostTroubleBillCellIdentifier];
            [self configurePostTroubleBillCell:cell atIndexPath:indexPath];
            return cell;
            
        }else if (indexPath.row == 1) {
            YWTroubleMissionFinishBillCell* cell = [tableView dequeueReusableCellWithIdentifier:YWTroubleMissionFinishBillCellIdentifier];
            [self configureTroubleFinishBillCell:cell atIndexPath:indexPath];
            return cell;
        }
    }else if (indexPath.section == 1){
        if (indexPath.row == 0) {
            YWObserveTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:YWObserveTableViewCellIdentifier];
            cell.troubleMissionModel = self.troubleMissionModel;//参与人cell
            return cell;
        }else{
            if (indexPath.row == 1) {
                YWMeterReadingDetailRecordCell *cell = [tableView dequeueReusableCellWithIdentifier:YWMeterReadingDetailRecordCellIdentifier];
                NSString *count;
                if (self.replyArray.count>0) {
                    count = [NSString stringWithFormat:@"(%ld)",(unsigned long)self.replyArray.count];
                }else{
                    count = @"";
                }
                NSString *replyText = [NSString stringWithFormat:@"评论%@:",count];
                cell.contentLabel.text = replyText;
                cell.contentLabel.textColor = [UIColor customTextGrayColor];
                return cell;
            }
            YWNewReplyTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:YWNewReplyTableViewCellIdetifer];
            YWReply *reply = self.dataSource[indexPath.section][indexPath.row];
            cell.reply = reply;
            return cell;
        }
    }else if (indexPath.section == 2) {
        YWTroubleMutableBIllCell* cell = [tableView dequeueReusableCellWithIdentifier:YWTroubleMutableBIllCellIdentifier];
        //        上下线的显示
        NSArray *rowArray = self.dataSource[indexPath.section];
        cell.isFirstRow = NO;
        if (indexPath.row == 0) {
            showTopLine = NO;
            showBottomLine = YES;
            cell.isFirstRow = YES;
        } else if (indexPath.row == (rowArray.count - 1)){
            showTopLine = YES;
            showBottomLine = NO;
        } else {
            showTopLine = YES;
            showBottomLine = YES;
        }
        UIView *topLine = (UILabel *)[cell viewWithTag:KTopLineTag];
        UIView *bottomLine = (UILabel *)[cell viewWithTag:KBottomLineTag];
        topLine.hidden = !showTopLine;
        bottomLine.hidden = !showBottomLine;
        //        cell赋值
        [self configureTroubleMutableBIllCell:cell atIndexPath:indexPath];
        return cell;
    }else{
        return [[UITableViewCell alloc] init];
    }
    return [[UITableViewCell alloc] init];
}
#pragma configure cell
- (void)configurePostTroubleBillCell:(YWPostTroubleBillCell *)cell atIndexPath:(NSIndexPath *)indexPath {
    cell.fd_enforceFrameLayout = NO;
    cell.delegate = self;
    cell.reportTrouble = self.troubleMissionModel.trouble;
}

- (void)configureTroubleFinishBillCell:(YWTroubleMissionFinishBillCell *)cell atIndexPath:(NSIndexPath *)indexPath {
    cell.fd_enforceFrameLayout = NO;
    cell.troubleMissionModel = self.troubleMissionModel;
    cell.fieldRecordContent = self.fieldRecordContent;
}
- (void)configureTroubleMutableBIllCell:(YWTroubleMutableBIllCell *)cell atIndexPath:(NSIndexPath *)indexPath {
    cell.fd_enforceFrameLayout = NO;
    YWCirculationInfo *circulationInfoc = self.dataSource[indexPath.section][indexPath.row];
    cell.troubleMissionModel = self.troubleMissionModel;
    cell.circulationInfo = circulationInfoc;
}

#pragma mark - UITableViewDataDelegate mothods
//- (CGFloat)tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath
//{
//    if (indexPath.section == 0) {
//        if (indexPath.row == 0) {
//            return [tableView fd_heightForCellWithIdentifier:YWPostTroubleBillCellIdentifier cacheByIndexPath:indexPath configuration:^(YWPostTroubleBillCell *cell) {
//                [self configurePostTroubleBillCell:cell atIndexPath:indexPath];
//            }];
//            
//        }else if (indexPath.row == 1) {
//            return [tableView fd_heightForCellWithIdentifier:YWTroubleMissionFinishBillCellIdentifier cacheByIndexPath:indexPath configuration:^(YWTroubleMissionFinishBillCell *cell) {
//                [self configureTroubleFinishBillCell:cell atIndexPath:indexPath];
//            }];
//        }
//    } else if (indexPath.section == 1) {
//        return [tableView fd_heightForCellWithIdentifier:YWTroubleMutableBIllCellIdentifier cacheByIndexPath:indexPath configuration:^(YWTroubleMutableBIllCell *cell) {
//            [self configureTroubleMutableBIllCell:cell atIndexPath:indexPath];
//        }];
//    }else{
//        return 60;
//    }
//    return 0.0;
//}

- (void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}


- (void)clickPostTroubleMobileWithNumber:(NSString *)mobileNumber{
    if (mobileNumber.length) {
        NSURL *phoneURL = [NSURL URLWithString:[NSString stringWithFormat:@"tel://%@",mobileNumber]];
        if ( !phoneCallWebView ) {
            phoneCallWebView = [[UIWebView alloc] initWithFrame:CGRectZero];// 这个webView只是一个后台的 不需要add到页面上来  效果跟方法二一样 但是这个方法是合法的
        }
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [phoneCallWebView loadRequest:[NSURLRequest requestWithURL:phoneURL]];
        });
    }else{
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"没有此联系人的电话号码" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"好" style:UIAlertActionStyleCancel handler:nil];
        [alert addAction:cancel];
        [self presentViewController:alert animated:YES completion:nil];
    }
}

- (void)didReceiveMemoryWarning{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
